package dbopr

import (
	"errors"
	"myCloud/dbmodel"
)

type FileProvider struct{}

func NewFileProvider() *FileProvider {
	return &FileProvider{}
}

func (p *FileProvider) FindByAlbum(albumID int) ([]dbmodel.File, error) {
	var out []dbmodel.File

	err := dbSession.Where("album_id=?", albumID).Find(&out).Error
	return out, err
}

// TODO: 有可能找到多个
func (*FileProvider) GetByHash(hash string) (*dbmodel.File, bool, error) {
	var out dbmodel.File
	query := dbSession.Where("hash=?", hash).First(&out)
	if query.RecordNotFound() {
		return nil, true, nil
	}
	return &out, false, query.Error
}

func (*FileProvider) GetByID(fileID int) (*dbmodel.File, bool, error) {
	var out dbmodel.File
	query := dbSession.Where("id=?", fileID).First(&out)
	if query.RecordNotFound() {
		return nil, true, nil
	}
	return &out, false, query.Error
}

func (p *FileProvider) Create(r *dbmodel.File) error {
	if r.ID != 0 {
		return errors.New("create record, but id not empty")
	}
	return dbSession.Create(r).Error
}

func (p *FileProvider) GetById(fileID int) (*dbmodel.File, bool, error) {
	var out dbmodel.File
	query := dbSession.Where("id=?", fileID).First(&out)
	if query.RecordNotFound() {
		return nil, true, nil
	}
	return &out, false, query.Error
}

func (*FileProvider) RemoveFile(fileID int) error {
	if fileID == 0 {
		return errors.New("fileID empty!")
	}
	f := &dbmodel.File{}
	f.ID = uint(fileID)
	return dbSession.Delete(f).Error
}
